import {
  Carousel,
  Button,
  Tooltip,
  Typography,
  Tabs,
  message,
  Spin,
  Pagination,
  Row,
  Col,
  Flex,
} from "antd";
import { ReloadOutlined, UserOutlined } from "@ant-design/icons";
import to from "await-to-js";
import React, { useEffect, useState, useRef } from "react";
import {
  getSlideshowList as getSlideshowListApi,
  getHotVideoList as getHotVideoListApi,
  getCategoryList as getCategoryListApi,
  getCategoryVideoList as getCategoryVideoListApi,
} from "@/api/home";
import { WebsiteBannerVo, WebsiteVideoVo } from "./types";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
const { Paragraph, Text } = Typography;
const Index: React.FC = () => {
  // 轮播图列表
  const [imgList, setImgList] = useState<WebsiteBannerVo[]>([]);
  // 热门视频列表
  const [hotVideoList, setHotVideoList] = useState<WebsiteVideoVo[]>([]);
  // 从全局获取用户信息
  const userInfo = useSelector((state) => state.user);
  // 路由跳转
  const navigateTo = useNavigate();
  // 控制加载状态
  const [spinning, setSpinning] = React.useState<boolean>(false);
  // 获取热门视频params
  const queryParams = useRef({
    // status: "0",
    pageSize: 6,
    pageNum: 1,
    auditState: "1",
    isAsc: "desc",
    orderByColumn: "createTime",
  });
  // 获取分类视频params
  const queryCategoryParams = useRef({
    categoryId: "",
    pageSize: 10,
    pageNum: 1,
    auditState: "1",
    isAsc: "desc",
    orderByColumn: "createTime",
  });
  // 获取分类列表params
  const getCategoryParams = useRef({
    pageSize: 10,
    pageNum: 1,
    orderByColumn: "createTime",
    isAsc: "desc",
  });
  // 获取分类列表
  const getCategoryList = async () => {
    const [err, res] = await to(getCategoryListApi(getCategoryParams.current));
    if (!err) {
      console.log(res);
      setCategoryList((categoryList) => {
        if (res.rows && res.rows.length > 0) {
          categoryList = res.rows;
          // 获取第一个分类的id
          firstCategoryId.current = categoryList[0].categoryId;
          if (queryCategoryParams.current.categoryId === "") {
            console.log(1, firstCategoryId.current);
            queryCategoryParams.current.categoryId = firstCategoryId.current;
            getCategoryVideoList();
          }
        }
        return categoryList;
      });
    }
  };
  // 挂载时调用
  useEffect(() => {
    getSlideshowList();
    getHotVideoList();
    getCategoryList();
  }, []);
  // 获取轮播图参数
  const querySwiperParams = useRef({
    title: "",
    isExhibition: "1",
    pageSize: 10,
    pageNum: 1,
    orderByColumn: "createTime",
    isAsc: "desc",
  });
  // 获取轮播图列表
  const getSlideshowList = async () => {
    const [err, res] = await to(getSlideshowListApi(querySwiperParams.current));
    if (!err) {
      console.log(res);
      setImgList((imgList) => {
        imgList = res.rows;
        return imgList;
      });
    }
  };
  // 获取热门视频列表
  const getHotVideoList = async () => {
    const [err, res] = await to(getHotVideoListApi(queryParams.current));
    if (!err) {
      setHotVideoList((hotVideoList: WebsiteVideoVo[]) => {
        hotVideoList = res.rows ?? [];
        console.log(hotVideoList);
        return hotVideoList;
      });
    }
  };
  // 视频播放按钮
  const handlePlay = (videoInfo: any) => {
    console.log(videoInfo);
    // 跳转页面并传递参数
    navigateTo("/home/playPage", { state: { videoInfo } });
  };
  const [total, setTotal] = useState(0);
  // 分类列表
  const [categoryList, setCategoryList] = useState([]);
  // 当前分类视频列表
  const [categoryVideoList, setCategoryVideoList] = useState([]);
  // 分类tab切换时
  const handleCategoryChange = async (activeKey: string) => {
    console.log(activeKey);

    queryCategoryParams.current = {
      categoryId: "",
      pageSize: 10,
      pageNum: 1,
      auditState: "1",
      isAsc: "desc",
      orderByColumn: "createTime",
    };
    setSpinning(true);
    // 查询当前分类的视频
    queryCategoryParams.current.categoryId = activeKey;
    await getCategoryVideoList();
    setSpinning(false);
  };
  const firstCategoryId = useRef("");
  // 获取分类视频列表
  const getCategoryVideoList = async () => {
    const [err, res] = await to(
      getCategoryVideoListApi(queryCategoryParams.current)
    );
    if (!err) {
      console.log(res);
      setTotal(res.total);
      setCategoryVideoList((categoryVideoList) => {
        categoryVideoList = res.rows ?? [];
        console.log(categoryVideoList);
        return categoryVideoList;
      });
      setSpinning(false);
    } else {
      message.error("获取分类视频失败");
      setSpinning(false);
    }
  };
  // 分页切换时
  const categoryPageChange = async () => {
    setSpinning(true);

    queryCategoryParams.current.pageNum += 1;
    await getCategoryVideoList();
    setSpinning(false);
  };
  return (
    <>
      <div className="flex mt-30px">
        <Row>
          <Col span={9}>
            <Carousel
              effect="fade"
              autoplay
              style={{ width: "510px", height: "340px" }}
            >
              {imgList.map((item: WebsiteBannerVo) => {
                return (
                  <div
                    style={{ width: "300px", height: "390px" }}
                    key={item.bannerId}
                  >
                    <img
                      style={{
                        borderRadius: "1%",
                        width: "100%",
                        height: "100%",
                        objectFit: "cover",
                      }}
                      src={item.linkUrl}
                      alt=""
                    />
                  </div>
                );
              })}
            </Carousel>
          </Col>
          <Col span={15}>
            <Flex gap={"small"}>
              <div className="flex flex-wrap ml-10px">
                {hotVideoList.map((item: WebsiteVideoVo) => {
                  return (
                    <div key={item.videoId} className="cursor-pointer w30%">
                      <div
                        onClick={() => handlePlay(item)}
                        className="ml-20px w225px h145px mb-5px"
                        style={{ borderRadius: "2%", border: "1px solid #999" }}
                      >
                        <img
                          src={item.images ?? ""}
                          alt=""
                          className="absolute w-223px h-144px object-contain"
                          style={{ borderRadius: "3%" }}
                        />
                        <Tooltip title="开始播放">
                          <img
                            style={{
                              width: "40px",
                              height: "40px",
                              marginLeft: "100px",
                              marginTop: "54px",
                            }}
                            className="absolute  cursor-pointer"
                            src={"bigplay.png"}
                            alt=""
                          />
                        </Tooltip>
                      </div>
                      <Paragraph
                        ellipsis={{ rows: 1, expandable: false }}
                        className="ml-20px w240px h-20px"
                        style={{
                          lineHeight: "20px",
                          fontWeight: "600",
                          color: "#444",
                        }}
                      >
                        {item.title}
                      </Paragraph>
                      <div
                        className="ml-20px mt--10px mb-10px"
                        style={{ color: "#666", fontSize: "14px" }}
                      >
                        <span>
                          <UserOutlined />
                          {item.createBy}
                        </span>
                        <span className="ml-20px">{item.createTime}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
              {/* <div style={{ backgroundColor: "pink" }}>
              <Tooltip title="刷新" style={{ backgroundColor: "pink" }}>
                <Button shape="circle" icon={<ReloadOutlined />} />
              </Tooltip>
            </div> */}
            </Flex>
          </Col>
        </Row>
      </div>
      <Spin tip="Loading" size="large" spinning={spinning}>
        <Tabs
          style={{
            borderTop: "1px solid #999",
            marginTop: "20px",
            paddingTop: "20px",
          }}
          defaultActiveKey="1"
          type="card"
          size={"small"}
          onChange={handleCategoryChange}
          items={categoryList.map((item) => {
            return {
              label: item.name,
              key: item.categoryId,
              children: (
                <>
                  <div className="flex flex-wrap">
                    {categoryVideoList.map((item: WebsiteVideoVo) => {
                      return (
                        <div key={item.videoId} className="cursor-pointer">
                          <div
                            onClick={() => handlePlay(item)}
                            className="mr-29px mt-40px w235px h145px mb-5px"
                            style={{
                              borderRadius: "2%",
                              border: "1px solid #999",
                            }}
                          >
                            <img
                              src={item.images ?? ""}
                              alt=""
                              className="absolute w-233px h-144px object-contain"
                              style={{ borderRadius: "3%" }}
                            />
                            <Tooltip title="开始播放">
                              <img
                                style={{
                                  width: "40px",
                                  height: "40px",
                                  marginLeft: "100px",
                                  marginTop: "54px",
                                }}
                                className="absolute  cursor-pointer"
                                src={"bigplay.png"}
                                alt=""
                              />
                            </Tooltip>
                          </div>
                          <Paragraph
                            ellipsis={{ rows: 1, expandable: false }}
                            className=" w240px h-20px"
                            style={{
                              lineHeight: "20px",
                              fontWeight: "600",
                              color: "#444",
                            }}
                          >
                            {item.title}
                          </Paragraph>
                          <div
                            className=" mt--10px mb-10px"
                            style={{ color: "#666", fontSize: "14px" }}
                          >
                            <span>
                              <UserOutlined />
                              {item.createBy}
                            </span>
                            <span className="ml-20px">{item.createTime}</span>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  <Pagination
                    showQuickJumper
                    defaultCurrent={1}
                    total={total}
                    onChange={categoryPageChange}
                  />
                </>
              ),
            };
          })}
        />
      </Spin>
    </>
  );
};

export default Index;
